/**
 * 时间格式化为倒计时时间
 **/
function formatTime(ms) {
    //计算出相差天数
    var days=Math.floor(ms/(24*3600*1000));
    //计算出小时数
    var leave1=ms%(24*3600*1000);
    var hours=Math.floor(leave1/(3600*1000));
    //计算相差分钟数
    var leave2=leave1%(3600*1000) ;
    var minutes=Math.floor(leave2/(60*1000));
    //计算相差秒数
    var leave3=leave2%(60*1000) ;
    var seconds=Math.round(leave3/1000);
    var formatTime = days+', '+hours+':'+minutes+':'+seconds;
    return formatTime;
}

/*
 * 根据参数生成提示和图片
 * type 红包类型  1 一档(88) 2 二挡(66) 3 三挡(18) 4 四挡 5 五档 6 六档
 * status 活动状态  -1: 异常 0：正常（抽中红包） 1:已领取红包 2：当天没有红包任务活动 3：时间未到任务没有完成 4：时间未到任务已完成 5:时间到了任务未完成 6:活动已结束 7:红包全部抢完了 10:空包(未抽到红包)
 * money 红包金额
 * QRCodeImgUrl 领取二维码
**/
function getContent(status, type, money, QRCode) {
    var title, countdownBox, modalFooter;
    var content = {'title':null,'countdownBox':null, 'modalFooter':null} ;

    if(status==-1 || status==undefined){//异常
        showMsg('warn','系统异常！');
    }else if(status==0 || status==7 || status==10){//抽中&没抽中&空包
        if(type==0){
            title = '红包溜走了';
            countdownBox = '<span>别灰心，下次再接再厉</span>';
            modalFooter = '<img class="cry" src="resources/img/luckDraw/mcz.gif"><a href="#" onclick="specification()">查看活动详情</a>';
        }else {
            title = '恭喜您';
            if(type==1 || type==2){//单独红包大奖
                countdownBox = '<span>获得<span>'+money+'</span>元红包</span>';
            }else{
                countdownBox = '<span>获得<span>'+money+'</span>元微信群红包</span>';
            }
            modalFooter = '<img class="QRCode" src="resources/img/luckDraw/'+QRCode+'"><p>扫码领取微信红包</p>';
        }
    }else if(status==1){//已抽过
        title = '亲，红包机会已用完';
        if(money==0){
            countdownBox = '<span>下次再来哦~</span>';
            modalFooter = '<img class="lookThis" src="resources/img/luckDraw/ckxq.gif"><a href="#" onclick="specification()">查看活动详情</a>';
        }else {
            if(type==1 || type==2){
                countdownBox = '<span>（注：上次抽中<span>'+money+'</span>元红包）</span>';
            }else{
                countdownBox = '<span>（注：上次抽中<span>'+money+'</span>元微信群红包）</span>';
            }
            modalFooter = '<img class="QRCode" src="resources/img/luckDraw/'+QRCode+'"><p>扫码领取微信红包</p>';
        }

    }else if(status==2){//当天没有红包活动
        showMsg('warn','今天没有红包活动，请刷新界面');
        $('#activeEntry').hide();
    }else if(status==3 || status==4){//3：时间未到任务没有完成 4：时间未到任务已完成
        title = '亲，距离领红包';
        var CountDown = formatTime(startTimeSlot);//10,3:59:12格式
        countdownBox = '<span class="font">还有</span><div class="countdown">'+CountDown+'</div>';
        if(status==3){
            modalFooter = '<p class="status">而且您还未完成任务哦</p><img class="lookThis" src="resources/img/luckDraw/ckxq.gif"><a href="#" onclick="specification()">查看任务详情</a>';
        }else {
            modalFooter = '<img class="lookThis" src="resources/img/luckDraw/ckxq.gif"><a href="#" onclick="specification()">查看任务详情</a>';
        }
    }else if(status==5){//5:时间到了任务未完成
        title = '亲，抱歉';
        countdownBox = '<span>完成任务才能领取红包哦</span>';
        modalFooter = '<img class="lookThis" src="resources/img/luckDraw/ckxq.gif"><a href="#" onclick="specification()">查看任务详情</a>';
    }else if(status==6){
        showMsg('warn','请刷新界面！');//应该不会有按钮可以点击了，会显示在首页中奖名单
    }else if(status==8){//没有权限
        title = '亲，抱歉';
        countdownBox = '<span>您不参与此活动哦</span>';
        modalFooter = '<img class="cry" src="resources/img/luckDraw/mcz.gif"><a href="#" onclick="specification()">查看活动详情</a>';
    }

    content.title = title;
    content.countdownBox = countdownBox;
    content.modalFooter = modalFooter;
    return content;
}

/**
 * 抽奖
 * type 红包类型  1 一档 2 二挡 3 三挡 4 四挡 5 五档 6 六档
 * status 活动状态  -1: 异常 0：正常（抽中红包） 1:已领取红包 2：当天没有红包任务活动 3：时间未到任务没有完成 4：时间未到任务已完成 5:时间到了任务未完成 6:活动已结束 7:红包全部抢完了 8:黑名单用户 10:空包(未抽到红包)
 * money 红包金额
 * QRCodeImgUrl 领取二维码
 **/
function LuckDraw(status, type, money, QRCode) {
    var content;
    if(status==666){
        content = '<div class="LuckDraw-content">\n' +
            '           <img class="QRCode" src="resources/img/luckDraw/loading.gif">'+
            '      </div>';
    }else {
        c = getContent(status, type, money, QRCode);
        content = '<div class="LuckDraw-content">\n' +
            '           <h1>'+c.title+'</h1>\n' +
            '           <div class="countdownBox">'+c.countdownBox+'</div>\n' +
            '           <div class="modal-footer">'+c.modalFooter+'</div>\n' +
            '      </div>';
    }
    var LuckDraw = '<div class="modal simpleModal disposableModal LuckDraw LuckDraw-'+status+'" id="lotteryModal">\n' +
        '               <div class="modal-dialog">\n' +
        '                   <div class="modal-header">\n' +
        '                       <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>\n' +
        '                   </div>\n' +
        '                   <div class="modal-body">\n' +
        '                       <img class="LuckDraw-bg" src="resources/img/luckDraw/modal-bg.png">\n' +
        '                       <img class="UAP" src="resources/img/luckDraw/UAP.png">\n' +
                                content +//填充内容
        '                   </div>\n' +
        '               </div>\n' +
        '           </div>';

    $('body').append(LuckDraw);
    //倒计时
    if($('.countdown').length>0){
        $('.countdown').countDown({
            css_class: 'countdown-alt',
            label_dd:'',
            label_hh:'',
            label_mm:'',
            label_ss:'',
            separator_days:':'
        });
    }

    if(c.title && c.countdownBox && c.modalFooter){
        $('#lotteryModal').modal('show');
    }

    if(status==0){
        $('#lotteryModal').addClass('Winning');
    }
}

/*跑马灯*/
function AutoScroll(obj) {
    $(obj).find("ul:first").animate({
            marginTop: "-23px"
        },
        2000,
        function() {
            $(this).css({
                marginTop: "0px"
            }).find("li:first").appendTo(this);
        });
}

/*展示抽奖结果*/
function showList() {
    var list = '<div class="module ui-icon-notice LuckDraw-module" id="lotteryResults">\n' +
        '                        <div class="module-content">\n' +
        '                            <div class="title"></div>'+
        '                            <div class="resultsBox">\n' +
        '                                <ul class="winnerList"></ul>\n' +
        '                                <div class="carouselList">\n' +//滚动中奖名单
        '                                    <ul></ul>\n' +
        '                                </div>\n' +
        '                            </div>\n' +
        '                        </div>\n' +
        '                    </div>';

    $.ajax({
        url: LOGSTATISTICS_SERVICE_URL+'redEnvelopes/winnersList',
        type: "POST",
        contentType: 'application/json',
        success: function (data) {
            if($('#lotteryResults').length>0){
                $('#lotteryResults .winnerList').empty();
                $('#lotteryResults .carouselList ul ').empty();
            }
            $('#activeEntry').replaceWith(list);
            var count = 2;//固定档位
            var resultList = new Array();
            $.each(data.body,function(index,item){
                resultList.push({'type':item.type, 'userCode':item.userCode, 'money':item.money});
            });
            resultList.sort(function(a,b){
                return b.money - a.money;
            });

            $.each(resultList,function(index,item){
                if(item.type <= count){
                    var $li = '<li><span class="usernum">'+item.userCode+'</span><span class="source">'+item.money+'<b>元</b></span></li>';
                    $('#lotteryResults .winnerList').append($li);
                }else {
                    var $li = '<li><span class="usernum">'+item.userCode+'</span><span class="source">'+item.money+'<b>元</b>微信群红包</span></li>';
                    $('#lotteryResults .carouselList ul').append($li);
                }
            });

            //滚动名单
            setInterval('AutoScroll("#lotteryResults .carouselList")', 1000);
        },
        error:function () {
            console.log('红包列表展示失败');
        }
    });
}

/*展示查看活动详情*/
function specification() {
    var specificationModal = '<div id="specification" class="modal simpleModal disposableModal">\n' +
        '        <div class="modal-dialog">\n' +
        '            <div class="modal-header">\n' +
        '                <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>\n' +
        '            </div>\n' +
        '            <div class="modal-body">\n' +
        '                <img class="LuckDraw-bg" src="resources/img/luckDraw/hdxq.png">\n' +
        '                <img class="UAP" src="resources/img/luckDraw/UAP.png">'+
        '            </div>\n' +
        '        </div>\n' +
        '    </div>';
    $('body').append(specificationModal);
    $("#specification").modal('show');
}

/*倒计时到活动结束时间的时候，首页展示中奖名单*/
function reduceTime(time) {
    var flag = setInterval(function(){
        time = time - 1000;
        if(time <= 0 ){
            showList();
            // console.log('抽奖活动结束,展示名单');
            clearInterval(flag);
            }
        }
        ,1000);
}

/*点击立即领取按钮*/
function forPicking() {
    $.ajax({
        url: LOGSTATISTICS_SERVICE_URL+'redEnvelopes/openRedEnvelopes',
        type: "POST",
        dataType: "json",
        send:function(){
            /*显示加载*/
            setTimeout(function () {
                LuckDraw(666, 0, 0, 0);
            }, 1000);
        },
        success: function (data) {
            $('.LuckDraw-666').modal('hide');
            LuckDraw(data.body.status, data.body.type, data.body.money, data.body.qrCodeImgUrl);
        },
        complete:function(){

        },
        error:function(){
            $('.LuckDraw-666').modal('hide');
            showMsg('warn','网速不给力，请刷新界面');
            console.log('抽红包接口调用失败');
        }
    });
}

var startTimeSlot;
/*获取当前任务*/
function getCurrentTask() {
    /*获取任务*/
    $.ajax({
        url: LOGSTATISTICS_SERVICE_URL+'redEnvelopes/getRedEnvelopesActivity',
        type: "POST",
        dataType: "json",
        success: function (data) {
            // console.log('刷新一次任务');
            if(data.body){
                $('#activeEntry').show();
                var currentSystem =  new Date(data.body.currentSystem.replace(/-/g,"/")).getTime();//服务器时间
                var receiveStartTime = new Date(data.body.receiveStartTime.replace(/-/g,"/")).getTime();
                var receiveStopTime = new Date(data.body.receiveStopTime.replace(/-/g,"/")).getTime();
                var SurplusTime = receiveStopTime - currentSystem;//距离活动结束时间段
                startTimeSlot = receiveStartTime - currentSystem; //距离活动开始时间段
                //活动结束，展示名单
                if(SurplusTime<=0){
                    showList();
                }else if(SurplusTime>0){
                    reduceTime(SurplusTime);
                }
                //活动未开始
                if(startTimeSlot>0){
                    var flag = setInterval(function(){
                            startTimeSlot = startTimeSlot - 1000;
                            if(startTimeSlot <= 0 ){
                                clearInterval(flag);
                            }
                        }
                        ,1000);
                }else if(startTimeSlot<0){
                    startTimeSlot=0;
                }
            }else {
                // console.log('当天没有红包活动,该模块隐藏');
            }
        },
        error:function () {
            console.log('红包时间接口调用失败');
}
    });
}
$(function () {
    getCurrentTask();
    //每1小时请求一次任务
    setInterval(function(){
       getCurrentTask();
       }
        ,1*60*60*1000);//1*60*60*1000
});